package com.maomao.admin.service.system;


import com.maomao.admin.common.core.text.Convert;
import com.maomao.admin.common.utils.ServletUtils;
import com.maomao.admin.common.utils.StringUtils;
import com.querydsl.core.types.Order;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.jpa.impl.JPAQuery;

public class AbstractPageService {

    /**
     * 当前记录起始索引
     */
    public static final String PAGE_NUM = "pageNum";

    /**
     * 每页显示记录数
     */
    public static final String PAGE_SIZE = "pageSize";

    /**
     * 排序列
     */
    public static final String ORDER_BY_COLUMN = "orderByColumn";

    /**
     * 排序的方向 "desc" 或者 "asc".
     */
    public static final String IS_ASC = "isAsc";


    protected <T> void startPage(JPAQuery<T> jpaQuery) {
        Integer page = Convert.toInt(ServletUtils.getParameter(PAGE_NUM), 1);
        Integer size = Convert.toInt(ServletUtils.getParameter(PAGE_SIZE), 10);
        jpaQuery.limit(size).offset((long) (page - 1) * size);
        OrderSpecifier orderSpecifier = orderSpec();
        if (orderSpecifier != null) {
            jpaQuery.orderBy(orderSpecifier);
        }
    }


    public static OrderSpecifier orderSpec() {
        // orderBy just like "createTime desc"
        String asc = ServletUtils.getParameter(IS_ASC);
        Order order = Order.ASC;
        if ("desc".equalsIgnoreCase(asc)) {
            order = Order.DESC;
        }
        String column = ServletUtils.getParameter(ORDER_BY_COLUMN);
        if (StringUtils.isNotBlank(column)) {
            return new OrderSpecifier(order, Expressions.path(Object.class, column));
        }
        return null;
    }

}
